<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NFlex,
  NSelect,
  NTree,
  NTreeSelect,
  useMessage,
  NButton,
  NUpload,
  NImage,
  NSwitch,
  NAvatar,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import { getToken } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import { useRoute } from 'vue-router'
import { TRUE } from 'sass'
import { router } from '@/router'
const route = useRoute()
import { format } from 'date-fns'
import { useTagsStore } from '@/store'
const tagsStore = useTagsStore()


defineOptions({ name: '对象模版编辑' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
  handleSave,
} = useCRUD({
  name: '对象编辑',
  initForm: {},
  doCreate: api.createSettingDesigner,
  doUpdate: api.updateSettingDesigner,
  doDelete: api.deleteSettingDesigner,
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  sevendayOption: [
    {
      id: 0,
      name: '是',
    },
    {
      id: 1,
      name: '否',
    },
  ],
  uploadAction: base_path + 'api/appointment/designer/file',
  token: getToken(),
  row: [],
  CityData: [],
  designerData: [],
  dateOptions: [],
  project_roles_options: [],
  typeData: [],
  brandOption: [],
  growData: [],
  expressData: [],
  levelData: [],
  onLevelData: [],
  infor_ggData: [],
  infor_msData: [],
  fileList: [],
})
const onCreate = () => {
  return {
    space_id: '',
    dates: '',
    interval: '',
    start: null,
    end: null,
  }
}
const onCreate_after = () => {
  return {
    start: null,
    end: null,
    con: '',
  }
}

function on_save() {
  handleSave()
}

async function get_data(id) {
  let ret = await api.getSettingDesignerById({ data_id: id })
  data.row = ret.data
  handleEdit(data.row)
  data.fileList.value = [
    {
      id: 1,
      name: '封面',
      url: data.row.picture,
      status: 'finished',
    },
  ]
}
function on_list() {
  tagsStore.removeTag(route.fullPath)
  router.push('/appointment/settings/designer')
}

onMounted(() => {
  const id = route.query.id
  modalVisible.value = true
  if (id > 0) {
    get_data(id)
  } else {
    handleAdd()
  }
  api.getSpaceList().then((res) => (data.CityData.value = res.data))
  api.getDesignerList().then((res) => (data.designerData.value = res.data))
  api.getSettingProjectTree().then((res) => (data.project_roles_options = res.data))
  api.getDesignerTypeList().then((res) => (data.typeData = res.data))

  $table.value?.handleSearch()
})

watch(modalVisible, (newValue, oldValue) => {
  if (!modalVisible.value) {
    tagsStore.removeTag(route.fullPath)
    router.push('/appointment/settings/designer')
  }
})
//处理多个日期
const today = new Date()
for (let i = 0; i < 30; i++) {
  const date = new Date(today)
  date.setDate(today.getDate() + i)
  data.dateOptions.push({ label: format(date, 'yyyy-MM-dd'), value: format(date, 'yyyy-MM-dd') })
}
const upValuedate = (value) => {
  modalForm.value.dates = value
}
//获取上级部门id
async function onleves(query) {
  let val = await api.getLeves({ key: query })
  data.onLevelData = val.data
}
//异步下拉获取上级
const loadingRef = ref(false)
const optionsRef = ref([])
const handleLeves = (query) => {
  if (!query.length) {
    optionsRef.value = []
    return
  }
  onleves(query)
  loadingRef.value = true
  // data.selectValue
  window.setTimeout(() => {
    data.onLevelData.value = data.onLevelData.filter((item) => ~item.label.indexOf(query))
    loadingRef.value = false
  }, 1e3)
}
//图文信息
const message = useMessage()
const customRequestMethod1 = (options) => {
  console.log(options, 'options')

  const { file } = options.file
  const formData = new FormData()
  formData.append('file', file)
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data, 'datatat')
      if (data.code == 200) {
        modalForm.value.picture = data.data.url
        message.success('封面图上传成功')
        options.onProgress(data)
      } else {
        message.error(data.msg)
      }
    })
}
const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}
//格式化关联商品选中
function flattenTree(list) {
  const result = []
  function flatten(_list = []) {
    _list.forEach((item) => {
      result.push(item)
      flatten(item.children)
    })
  }
  flatten(list)
  return result
}
const renderSourceList = function ({ onCheck, pattern }) {
  return h(NTree, {
    style: 'margin: 0 4px;',
    keyField: 'value',
    checkable: true,
    selectable: true,
    blockLine: true,
    checkOnClick: true,
    cascade: true,
    data: data.project_roles_options,
    pattern,
    checkedKeys: modalForm.project_roles,
    onUpdateCheckedKeys: (checkedKeys) => {
      onCheck(checkedKeys)
    },
  })
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: ['input', 'blur'],
    },
  ],
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="编辑对象信息">
    <NForm
      ref="modalFormRef"
      label-placement="left"
      label-align="left"
      :label-width="150"
      :model="modalForm"
      size="large"
      :rules="validateAddUser"
    >
      <n-card content-style="padding: 0;">
        <n-tabs type="line" animated size="large" :tabs-padding="20" pane-style="padding: 20px;">
          <n-tab-pane name="基础信息">
            <NFormItem label="排序" path="sort">
              <NInputNumber
                style="width: 200px"
                v-model:value="modalForm.sort"
                clearable
                placeholder="输入排序"
                :default-value="0"
              />
            </NFormItem>
            <NFormItem label="姓名" path="name" style="width: 100%">
              <NInput v-model:value="modalForm.name" clearable placeholder="请输入姓名" />
            </NFormItem>
            <NFormItem label="称号" path="title" style="width: 100%">
              <NInput v-model:value="modalForm.title" clearable placeholder="请输入称号" />
            </NFormItem>
            <NFormItem label="简介" path="intro">
              <NInput
                style="width: 590px"
                type="textarea"
                v-model:value="modalForm.intro"
                clearable
                placeholder="请输入备注"
              />
            </NFormItem>
            <NFormItem label="所属门店" path="type">
              <NSelect
                style="width: 400px"
                multiple
                v-model:value="modalForm.space_id"
                :options="data.CityData.value"
                placeholder="请选择所属门店"
              />
            </NFormItem>

            <NFormItem label="对象类型" path="type">
              <NSelect
                style="width: 200px"
                v-model:value="modalForm.type"
                :options="data.typeData"
                placeholder="请选择对象类型"
              />
            </NFormItem>
            <NFormItem label="医生类别" v-if="modalForm.type == 3" path="doctor_type">
              <NSelect
                multiple
                style="width: 200px"
                v-model:value="modalForm.doctor_type"
                :options="data.designerData.value"
                placeholder="请选择医生类别"
              />
            </NFormItem>

            <NFormItem label="头像封面" path="picture" style="width: 100%">
              <NUpload
                :action="data.uploadAction"
                :headers="{ token: data.token }"
                :max="1"
                :custom-request="customRequestMethod1"
                list-type="image-card"
                v-model:file-list="data.fileList.value"
                :show-file-list="true"
              >
              </NUpload>
            </NFormItem>
            <NFormItem label="介绍组图" path="images" style="width: 100%">
              <NUpload
                :action="data.uploadAction"
                :headers="{ token: data.token }"
                multiple
                list-type="image-card"
                @finish="handleFinish"
                v-model:file-list="modalForm.images"
              >
              </NUpload>
            </NFormItem>
          </n-tab-pane>
<!--          <n-tab-pane name="时间排班属性">-->
<!--            <NFormItem label="门店排班" path="open_roles">-->
<!--              <n-layout>-->
<!--                <n-layout-header>-->
<!--                  <n-flex>-->
<!--                    <n-tag size="large" style="width: 120px"> 门店 </n-tag>-->
<!--                    <n-tag size="large" style="width: 400px"> 开放日期 </n-tag>-->
<!--                    <n-tag size="large" style="width: 100px"> 时间间隔 </n-tag>-->
<!--                    <n-tag size="large" style="width: 274px"> 每日时间段 </n-tag>-->
<!--                  </n-flex>-->
<!--                </n-layout-header>-->
<!--                <n-layout-content content-style="padding: 10px 0;">-->
<!--                  <n-dynamic-input v-model:value="modalForm.open_roles" :on-create="onCreate">-->
<!--                    <template #default="{ value }">-->
<!--                      <n-flex justify="space-between" align="center">-->
<!--                        <NSelect-->
<!--                          style="width: 120px"-->
<!--                          v-model:value="value.space_id"-->
<!--                          :options="data.CityData.value"-->
<!--                          placeholder="请选择所属门店"-->
<!--                        />-->
<!--                        <n-select-->
<!--                          style="width: 400px"-->
<!--                          v-model:value="value.dates"-->
<!--                          :options="data.dateOptions"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          multiple-->
<!--                          placeholder="选择多个日期"-->
<!--                          @update-value="upValuedate"-->
<!--                        />-->
<!--                        <NInputNumber-->
<!--                          style="width: 100px"-->
<!--                          v-model:value="value.interval"-->
<!--                          clearable-->
<!--                          placeholder="输入时间间隔"-->
<!--                          :default-value="0"-->
<!--                        />-->
<!--                        <n-time-picker-->
<!--                          style="width: 120px"-->
<!--                          v-model:formatted-value="value.start"-->
<!--                          value-format="HH:mm"-->
<!--                          placeholder="选择开始时间"-->
<!--                        />-->
<!--                        <div>~</div>-->
<!--                        <n-time-picker-->
<!--                          style="width: 120px"-->
<!--                          v-model:formatted-value="value.end"-->
<!--                          value-format="HH:mm"-->
<!--                          placeholder="选择结束时间"-->
<!--                        />-->
<!--                      </n-flex>-->
<!--                    </template>-->
<!--                  </n-dynamic-input>-->
<!--                </n-layout-content>-->
<!--              </n-layout>-->
<!--            </NFormItem>-->
<!--            <NFormItem label="休息" path="close_roles">-->
<!--              <n-layout>-->
<!--                <n-layout-header>-->
<!--                  <n-flex>-->
<!--                    <n-tag size="large" style="width: 462px"> 休息时间 </n-tag>-->
<!--                    <n-tag size="large" style="width: 300px"> 备注 </n-tag>-->
<!--                  </n-flex>-->
<!--                </n-layout-header>-->
<!--                <n-layout-content content-style="padding: 10px 0;">-->
<!--                  <n-dynamic-input-->
<!--                    v-model:value="modalForm.close_roles"-->
<!--                    :on-create="onCreate_after"-->
<!--                  >-->
<!--                    <template #default="{ value }">-->
<!--                      <n-flex justify="space-between" align="center">-->
<!--                        <n-date-picker-->
<!--                          v-model:formatted-value="value.start"-->
<!--                          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                          type="datetime"-->
<!--                          placeholder="选择开始时间"-->
<!--                          clearable-->
<!--                        />-->
<!--                        <div>~</div>-->
<!--                        <n-date-picker-->
<!--                          v-model:formatted-value="value.end"-->
<!--                          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                          type="datetime"-->
<!--                          placeholder="选择结束时间"-->
<!--                          clearable-->
<!--                        />-->
<!--                        <n-input-->
<!--                          style="width: 300px"-->
<!--                          v-model:value="value.con"-->
<!--                          placeholder="输入备注"-->
<!--                        />-->
<!--                      </n-flex>-->
<!--                    </template>-->
<!--                  </n-dynamic-input>-->
<!--                </n-layout-content>-->
<!--              </n-layout>-->
<!--            </NFormItem>-->
<!--          </n-tab-pane>-->
          <n-tab-pane name="项目配置">
            <NFormItem label="项目配置" path="project_roles">
              <n-transfer
                v-model:value="modalForm.project_roles"
                :options="flattenTree(data.project_roles_options)"
                :render-source-list="renderSourceList"
                source-filterable
              />
            </NFormItem>
          </n-tab-pane>
        </n-tabs>
      </n-card>
      <n-button :loading="loading" mt-20 type="primary" @click="on_list">返回列表</n-button>
      <n-button :loading="loading" mt-20 ml-15 type="primary" @click="on_save">保存</n-button>
    </NForm>
  </CommonPage>
</template>
